package org.wu.framework.javafx.spring.starter;


import jakarta.annotation.Resource;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;


@Slf4j
public class SpringJavaFxLauncher implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    private LazyJavaFxProperties lazyJavaFxProperties;

    @Resource
    private ConfigurableApplicationContext applicationContext;

    // 静态引用，用于在JavaFxApp中访问Spring上下文
    private static ConfigurableApplicationContext staticApplicationContext;
    private static LazyJavaFxProperties staticLazyJavaFxProperties;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 存储静态引用，供JavaFxApp使用
        staticApplicationContext = this.applicationContext;
        staticLazyJavaFxProperties = this.lazyJavaFxProperties;

        // 禁用Headless模式
        System.setProperty("java.awt.headless", "false");

        // 启动JavaFX应用
        try {
            new Thread(() -> Application.launch(JavaFxApp.class)).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 改为静态内部类，允许JavaFX实例化
    public static class JavaFxApp extends Application {
        @Override
        public void start(Stage stage) {
            // 创建WebView组件
            WebView webView = new WebView();
            WebEngine webEngine = webView.getEngine();

            // 配置错误处理
            webEngine.setOnError(error -> {
                log.error("网页加载错误: {}", error.getMessage());
                webEngine.loadContent("<h1>加载失败</h1><p>" + error.getMessage() + "</p>");
            });

            // 加载目标URL
            String url = staticLazyJavaFxProperties.getTargetUrl();
            log.info("加载 URL: {}", url);
            webEngine.load(url);

            // 配置窗口属性
            stage.setTitle(staticLazyJavaFxProperties.getWindow().getTitle());
            stage.setWidth(staticLazyJavaFxProperties.getWindow().getWidth());
            stage.setHeight(staticLazyJavaFxProperties.getWindow().getHeight());
            stage.setScene(new Scene(webView));

            // 窗口关闭时关闭Spring应用
            stage.setOnCloseRequest(e -> {
                staticApplicationContext.close();
                Platform.exit();
                System.exit(0);
            });

            // 显示窗口
            stage.show();
        }
    }
}
